package com.example;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;

class CustomClassLoader extends ClassLoader {

    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] b = loadClassData(name);
        return defineClass(name, b, 0, b.length);
    }

    private byte[] loadClassData(String className) {
        String fileName = className.substring(className.lastIndexOf('.') + 1) + ".class";
        try {
            // 假设类文件位于当前目录的"classes"文件夹下
            FileInputStream fis = new FileInputStream("classes/" + fileName);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int bytesRead;
            byte[] buffer = new byte[4096];
            while ((bytesRead = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
            fis.close();
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        CustomClassLoader classLoader = new CustomClassLoader();
        Class<?> helloWorldClass = classLoader.loadClass("com.example.HelloWorld");
        Object helloWorldInstance = helloWorldClass.newInstance();
        Method printHelloMethod = helloWorldClass.getMethod("printHello");
        printHelloMethod.invoke(helloWorldInstance);
    }
}
